﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using EzDesk.Utility.Json;

namespace EzDesk.Clients.Utility
{
    /// <summary>
    /// @Refactory 
    /// </summary>
    [Serializable]
    public class FeedClientModel
    {
        public string AppName{ get; set; }
        public Guid FeedId { get; set; }
        public DateTime CreateOn { get; set; }
        public DateTime UpdateOn { get; set; }
        public DateTime LastChangeOn { get; set; }
        public string IconUrl { get; set; }

        public bool IsRead { get; set; }
        public bool IsAvailable { get; set; }
        public bool IsMark { get; set; }
        public string Type { get; set; }
        
        public IList<KeyValuePair<string, string>> ExtensionData { get; set; }

        public FeedDataModel OriginalData { get; set; }
        /// <summary>
        /// @Refactory this property should be replaced be an virtual property for different client type.
        /// </summary>
        public FeedDataModel TransformedData { get; set; }
        public bool IsTransformed
        {
            get
            {
                return TransformedData != null;
            }
        }

        public static  FeedClientModel BuildFeedModel(XElement xmlData)
        {
            var model = new FeedClientModel();
            model.FeedId = new Guid(xmlData.Attribute("guid").Value);
            model.CreateOn = Convert.ToDateTime(xmlData.Attribute("createon").Value);
            model.UpdateOn = Convert.ToDateTime(xmlData.Attribute("updateon").Value);
            model.LastChangeOn = Convert.ToDateTime(xmlData.Attribute("lastchangeon").Value);
            model.IsAvailable = Convert.ToBoolean(xmlData.Attribute("isavailable").Value);
            model.IsRead = Convert.ToBoolean(xmlData.Attribute("isread").Value);
            model.IsMark = Convert.ToBoolean(xmlData.Attribute("ismark").Value);
            model.IconUrl = Convert.ToString(xmlData.Attribute("iconurl").Value);

            model.Type = xmlData.Attribute("type").Value;
            model.ExtensionData = JsonHelper.JsonToDictionary(xmlData.Element("data").Value).ToList();

            model.OriginalData = new FeedDataModel();
            model.OriginalData.Title = DesignFix(xmlData.Element("title").Value);
            model.OriginalData.Body = DesignFix(xmlData.Element("body").Value);
            return model;
        }

        //@Refactory [These 2 lines should be move to Class: XamlFeedTransform]
        private const string XmlRootTemplate = "<root>{0}</root>";
        private static string DesignFix(string str)
        {
            return string.Format(XmlRootTemplate, str);
        }
    }
}
